package com.loongtech.bi.action.flow;

import com.loongtech.bi.action.Base2BiSearchAction;
import com.loongtech.bi.manager.flow.HadoopQueryManager;
import com.loongtech.bi.manager.system.GameParamConfigManager;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.bi.support.CommonGameParam;
import com.loongtech.bi.support.Session;
import com.loongtech.core.util.Time;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import java.util.*;
import java.util.Map.Entry;

/**
 * 流水查询—账号信息流水Action
 * @author Marin
 * @date 2015年09月17日
 */
@Controller
@Scope("view")
public class AccountInfoFlowAction extends Base2BiSearchAction {
	private static final long serialVersionUID = 1L;
	protected Date dateStart = new Date(Time.getBeginningOfDay(Time.currentTime() - 1 * Time.DAY));
	private AccountInfoFlow queryBean;  // 查询bean
	
	private List<Object[]> result;  // 结果List
		
	@Autowired
	HadoopQueryManager hadoopQueryManager;
	
	@Autowired
	private SysLogManager sysLogManager;
	@Autowired
	private Session session;
	
	@PostConstruct
	public void init() {
		queryBean = new AccountInfoFlow();
		result = new ArrayList<>();
	}
	
	public String getSchoolNameById(Object id) {
		if(StringUtils.isBlank((String)id)) {
			return "";
		}
		
		return GameParamConfigManager.getItemsRevise(CommonGameParam.SCHOOL).get(String.valueOf(id)); //SchoolManager.getSchoolNameById(Integer.parseInt(String.valueOf(id)));
	}
	
	public String getGenderById(Object genderId) {
		String str = String.valueOf(genderId);
		Map<String, String> revise = GameParamConfigManager.getItemsRevise(CommonGameParam.ROLEGENDER);
		
		return revise == null || revise.get(str) == null ? str : revise.get(str);
	}
	
	public void search()  {
		sysLogManager.addLog(session.getUserName(), "查询流水查询—账号信息流水");
		
		result = new ArrayList<>();
		
		FacesContext context = FacesContext.getCurrentInstance();
		
		// 用户ID，角色ID必要有一个非空
		if (StringUtils.isBlank(queryBean.getUserid()) && StringUtils.isBlank(queryBean.getRoleid()) && StringUtils.isBlank(queryBean.getRolename())) {
			context.addMessage(null, new FacesMessage("提示", "用户ID，角色ID,角色名称至少有一个非空!"));
			return;
		}
		
		if (HadoopQueryManager.VISIT_QUEUE.offer("accountInfoFlowAction")) {
			System.out.println("VISIT_QUEUE offer accountInfoFlowAction ok!");
			
			StringBuffer sql = new StringBuffer();
			sql.append("select a.logtime,a.platform,a.channel,a.serverid,a.userid,a.roleid,a.rolename,a.occupation,a.gender,b.afterlevel,b.viplevel,a.mac,b.updatetime from (select logtime,platform,channel,serverid,userid,roleid,rolename,occupation,gender,mac from rolecreate where 1=1 ");
			if (!StringUtils.isBlank(queryBean.getUserid())) {
				StringBuilder sb = new StringBuilder();
				StringTokenizer st = new StringTokenizer(queryBean.getUserid().trim());
				
				int index = 0;
				
				while(st.hasMoreTokens()) {
					if(index == 0) {
						sb.append("'").append(st.nextToken()).append("'");
					}else {
						sb.append(",'").append(st.nextToken()).append("'");
					}
					
					index ++;
				}
				
				sql.append(" and userid in (");
				sql.append(sb.toString());
				sql.append(") ");
			}
			
			if (!StringUtils.isBlank(queryBean.getRoleid())) {
				StringBuilder sb = new StringBuilder();
				StringTokenizer st = new StringTokenizer(queryBean.getRoleid().trim());
				
				int index = 0;
				
				while(st.hasMoreTokens()) {
					if(index == 0) {
						sb.append("'").append(st.nextToken()).append("'");
					}else {
						sb.append(",'").append(st.nextToken()).append("'");
					}
					
					index ++;
				}
				
				sql.append(" and cast(roleid as string) in (");
				sql.append(sb.toString());
				sql.append(") ");
			}
            if (!"0".equals(queryPlatform)) {
                sql.append(" and platform = ");
                sql.append(queryPlatform);
            }
            if (!"0".equals(queryChannel)) {
                sql.append(" and channel = '");
                sql.append(queryChannel);
                sql.append("' ");
            }
            if (!"0".equals(queryServer)) {
                sql.append(" and serverid = ");
                sql.append(queryServer);
            }
			if (!StringUtils.isBlank(queryBean.getRolename())) {
				StringBuilder sb = new StringBuilder();
				StringTokenizer st = new StringTokenizer(queryBean.getRolename().trim());
				
				int index = 0;
				
				while(st.hasMoreTokens()) {
					if(index == 0) {
						sb.append("'").append(st.nextToken()).append("'");
					}else {
						sb.append(",").append("'").append(st.nextToken()).append("'");
					}
					
					index ++;
				}
				
				sql.append(" and rolename in (");
				sql.append(sb.toString());
				sql.append(") ");
			}
			
			sql.append(" ) as a left join (select updatetime,userid,roleid,afterlevel,viplevel from totalrolelevelup where dt = '"+ Time.getDateStr(dateStart) +"') as b on a.userid = b.userid and a.roleid = b.roleid order by a.logtime asc");
			
			Entry<List<String>, List<Object[]>> ret = hadoopQueryManager.executeSQL(sql.toString());
			if (null == ret || null == ret.getKey() || ret.getKey().isEmpty() || null == ret.getValue()) {
				context.addMessage(null, new FacesMessage("提示", "查询结果为空!"));
				return;
			}
			
			result = ret.getValue();
		} else {
			System.out.println("VISIT_QUEUE offer accountInfoFlowAction failed!");
			context.addMessage(null, new FacesMessage("提示", "当前系统正被访问，为保证服务器稳定，请稍后再试"));
			return;
		}
	}
	
	public class AccountInfoFlow {
		private String logtime; // 时间
		private String hostname; // 服务器主机名
		private String modulename; // 模块名
		private int gameid; // 游戏ID
		private int serverid; // 服务器ID
		private long logid; // 日志编号
		private String logtype; // 日志类型
		private int platform; // 平台ID
		private String channel; // 渠道标识
		private String mac; // 设备mac地址
		private String userid; // 账号ID
		private String roleid; // 角色ID
		private String rolename; //角色名称
		
		public String getRolename() {
			return rolename;
		}

		public void setRolename(String rolename) {
			this.rolename = rolename;
		}

		public String getLogtime() {
			return logtime;
		}

		public void setLogtime(String logtime) {
			this.logtime = logtime;
		}

		public String getHostname() {
			return hostname;
		}

		public void setHostname(String hostname) {
			this.hostname = hostname;
		}

		public String getModulename() {
			return modulename;
		}

		public void setModulename(String modulename) {
			this.modulename = modulename;
		}

		public int getGameid() {
			return gameid;
		}

		public void setGameid(int gameid) {
			this.gameid = gameid;
		}

		public int getServerid() {
			return serverid;
		}

		public void setServerid(int serverid) {
			this.serverid = serverid;
		}

		public long getLogid() {
			return logid;
		}

		public void setLogid(long logid) {
			this.logid = logid;
		}

		public String getLogtype() {
			return logtype;
		}

		public void setLogtype(String logtype) {
			this.logtype = logtype;
		}

		public int getPlatform() {
			return platform;
		}

		public void setPlatform(int platform) {
			this.platform = platform;
		}

		public String getChannel() {
			return channel;
		}

		public void setChannel(String channel) {
			this.channel = channel;
		}

		public String getMac() {
			return mac;
		}

		public void setMac(String mac) {
			this.mac = mac;
		}

		public String getUserid() {
			return userid;
		}

		public void setUserid(String userid) {
			this.userid = userid;
		}

		public String getRoleid() {
			return roleid;
		}

		public void setRoleid(String roleid) {
			this.roleid = roleid;
		}
	}

	@Override
	protected String csvContent() {
		return null;
	}

	@Override
	protected String csvFileName() {
		return null;
	}

	public List<Object[]> getResult() {
		return result;
	}

	public void setResult(List<Object[]> result) {
		this.result = result;
	}

	public AccountInfoFlow getQueryBean() {
		return queryBean;
	}

	public void setQueryBean(AccountInfoFlow queryBean) {
		this.queryBean = queryBean;
	}

	public Date getDateStart() {
		return dateStart;
	}

	public void setDateStart(Date dateStart) {
		this.dateStart = dateStart;
	}
}
